﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using ServiceStack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.ConstrainedExecution;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using XuanXiang.Infrastructure.Attr;
using XuanXiang.Infrastructure.Dto.Request;
using XuanXiang.Infrastructure.Dto.Request.Login;
using XuanXiang.Infrastructure.Dto.Request.Merchant;
using XuanXiang.Infrastructure.Dto.Response;
using XuanXiang.Infrastructure.Dto.Response.Goods;
using XuanXiang.Infrastructure.Dto.Response.Merchant;
using XuanXiang.Infrastructure.Dto.Response.Supplier;
using XuanXiang.Infrastructure.EFCore.MySql;
using XuanXiang.Infrastructure.IOC;
using XuanXiang.Infrastructure.Redis;
using XuanXiang.Infrastructure.Tools;
using XuanXiang.Service.EFCore;
using XuanXiang.Service.Interface;

namespace XuanXiang.Service.Instance
{
    [Inject_]
    public class Merchant_Service : Base_Service, I_Merchant_Service
    {
        private readonly Sys_IOC _sys_IOC;
        private readonly RedisStringService _redisStringService;
        private readonly IConfiguration _configuration;
        private readonly RedisListService _redisListService;
        private readonly Promote_IOC _promote_IOC;
        private readonly Merchant_IOC _merchant_IOC;
        private readonly Goods_IOC _goods_IOC;
        private readonly Supplier_IOC _supplier_IOC;

        public Merchant_Service(Merchant_IOC merchant_IOC,
            Goods_IOC goods_IOC,
            Supplier_IOC supplier_IOC,
           Sys_IOC sys_IOC,
           RedisListService redisListService,
            Promote_IOC promote_IOC,
            RedisStringService redisStringService,
            IConfiguration configuration)
        {
            _sys_IOC = sys_IOC;
            _redisStringService = redisStringService;
            _configuration = configuration;
            _redisListService = redisListService;
            _promote_IOC = promote_IOC;
            _merchant_IOC = merchant_IOC;
            _goods_IOC = goods_IOC;
            _supplier_IOC = supplier_IOC;
        }



        /// <summary>
        /// 检查商户登录
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Merchant_Dto Check_Merchant_Login(string code, string account)
        {
            var redis = _configuration["Redis:Keys:Check_Merchant_Login"];


            //获取redis中的供应商信息
            var s = _redisStringService.Get<string>(code);
            if (!string.IsNullOrEmpty(s))
            {
                return JsonConvert.DeserializeObject<Merchant_Dto>(s)!;
            }



            var jwt = _redisStringService.Get<string>(redis + account);//code
            if (code == jwt)
            {
                //返回登录的用户信息
                var merchant = _merchant_IOC._merchant_EFCore.GetAll(d => d.MAccount == account)
                     .Select(d => new Merchant_Dto()
                     {
                         id = d.MId,
                         account = d.MAccount,
                         name = d.MName
                     }).Single();
                //将用户存在redis中
                _redisStringService.Set(code, JsonConvert.SerializeObject(merchant), DateTime.Now.AddSeconds(88520));
                return merchant;
            }
            else
            {
                return null;
            }

        }


        /// <summary>
        /// 商户登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Merchant_Logins(Login_dto dto)
        {
            var iq = _merchant_IOC._merchant_EFCore.GetAll(d => d.MAccount == dto.account);
            if (!await iq.AnyAsync())
            {
                return Get_Result(-1, "账号或者密码错误");
            }
            var merchant = await iq.SingleAsync();


            var pwd = EncryptUtil.LoginMd5(dto.password!, merchant.MSalt!);
            if (merchant.MPassword != pwd)
            {
                return Get_Result(-1, "账号或者密码错误");
            }

            if (merchant.MIsBan == 1)
            {
                return Get_Result(-1, "账号已禁用");
            }
            //保存到商户登录日志

            MerchantLoginLog merchantLoginLog = new MerchantLoginLog()
            {
                MLlid = Config.GUID(),
                MCreateTime = DateTime.Now,
                MLlcode = dto.code,
                MLlip = Config.GetIp(),
                MLlmid = merchant.MId
            };
            _merchant_IOC._merchant_LoginLogs_EFCore.Add(merchantLoginLog);
            if (merchant.MIsActive == 0)
            {
                merchant.MIsActive = 1;
                _merchant_IOC._merchant_EFCore.Update(merchant);
            }
            var result = _merchant_IOC._merchant_LoginLogs_EFCore.Transactions(_merchant_IOC._merchant_EFCore);

            //保存redis
            var jwt = _configuration["Redis:Keys:Check_Merchant_Login"];
            _redisStringService.Set<String>(jwt + merchant.MAccount, dto.code!, DateTime.Now.AddSeconds(86400));


            return Get_Result(result ? 0 : -1);

        }

        /// <summary>
        /// 新增商户
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> AddMerchant(Add_Merchant_Dto dto)
        {
            Merchant merchant = new Merchant()
            {
                MId = Config.GUID(),
                MAccount = dto.phone,
                MContacts = dto.contacts,
                MName = dto.name,
                MIsActive = 0,
                MCancelMoney = 0,
                MCancelOrderCount = 0,
                MCompleteOrderCount = 0,
                MCreateTime = DateTime.Now,
                MCurrMoney = 0,
                MIsBan = 0,
                MMoney = 0,
                MOpenId = null,
                MOrderCount = 0,
                MPassword = "123456",
                MSalt = null
            };
            _merchant_IOC._merchant_EFCore.Add(merchant);
          await  _merchant_IOC._merchant_EFCore.SaveChangesAsync();


            //初始化密码
           
                var salt = Config.GUID2();
                merchant.MSalt = salt;
                merchant.MPassword = EncryptUtil.LoginMd5("123456", salt);

            

            var result = await _merchant_IOC._merchant_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }

        /// <summary>
        /// 新增商品在购物车
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Add_MerchantCar(Add_Car_Dto dto)
        {
            var car = _merchant_IOC._car_EFCore.GetAll(d => d.CMId == dto.mid).SingleOrDefault();
            if (car == null)
            {
                //没有 新增一个购物车
                car = new Car()
                {
                    CId = Config.GUID(),
                    CMId = dto.mid,
                    CTotal = 0,
                    CCreateTime = DateTime.Now,
                    CLastTime = DateTime.Now
                };

                _merchant_IOC._car_EFCore.Add(car);
                _merchant_IOC._car_EFCore.SaveChanges();
            }

            //有

            //var c_id = _merchant_IOC._car_EFCore.GetAll(d => d.CMId == dto.mid).Select(d => d.CId).SingleOrDefault();
            var c_id = car.CId;
            //找到当前商户的所有购物车详情
            var carsdetail = _merchant_IOC._carDetails_EFCore.GetAll(d => d.CdCId == c_id && d.CdGId == dto.gid).SingleOrDefault();
            //判断是否有当前添加的商品

            if (carsdetail == null)
            {
                //没有
                //添加一条购物车详情
                carsdetail = new Carsdetail()
                {
                    CdId = Config.GUID(),
                    CdGId = dto.gid,
                    CdCId = c_id,
                    CdNumber = 1,
                    CdLastTime = DateTime.Now
                };

                _merchant_IOC._carDetails_EFCore.Add(carsdetail);
            }
            else
            {
                //有
                //找到相同的商品数量+1
                /*var details = _merchant_IOC._carDetails_EFCore.GetAll(d => d.CdGId == dto.gid && d.CdCId == c_id).SingleOrDefault();
                details.CdNumber = details.CdNumber + 1;*/
                carsdetail.CdNumber++;
                carsdetail.CdLastTime = DateTime.Now;
                _merchant_IOC._carDetails_EFCore.Update(carsdetail);

            }


            _merchant_IOC._carDetails_EFCore.SaveChanges();

            //修改购物车的商品数量
            //找到当前商户的购物车

            //获取当前购物车的所有数量
            car.CTotal = _merchant_IOC._carDetails_EFCore.GetAll(d => d.CdCId == c_id).Sum(d => d.CdNumber);
            car.CLastTime = DateTime.Now;

            var result = await _merchant_IOC._car_EFCore.SaveChangesAsync();
            return Get_Result(result);




        }

        /// <summary>
        /// 删除商户
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Delete_Merchant(Delete_Dto dto)
        {
            var data = await _merchant_IOC._merchant_EFCore.GetAll(d => d.MId == dto.id).SingleOrDefaultAsync();
            _merchant_IOC._merchant_EFCore.Delete(data);
            var result = await _merchant_IOC._merchant_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }


        /// <summary>
        /// 获取商户列表
        /// </summary>
        /// <param name="fenye_Dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Merchant(Fenye_Dto dto)
        {
            var data = await _merchant_IOC._merchant_EFCore
                  .GetAll(out int total, dto.page, dto.limit, false,
                  o => o.MOrderCount, d => d.MName.Contains(dto.key))
                  .Select(d => new merchant_dto
                  {
                      ID = d.MId,
                      isActive = d.MIsActive,
                      cancelMoney = d.MCancelMoney,
                      cancelOrderCount = d.MCancelOrderCount,
                      completeOrderCount = d.MCompleteOrderCount,
                      contacts = d.MContacts,
                      currMoney = d.MCurrMoney,
                      isBan = d.MIsBan == 1 ? true : false,
                      money = d.MMoney,
                      name = d.MName,
                      orderCount = d.MOrderCount,
                      time = d.MCreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss")
                  }).ToListAsync();

            return Get_Result(0, "ok", new
            {
                data = data,
                total = total
            });
        }

        /// <summary>
        /// 商户的禁用/启用
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> IsBan_Merchant(IsBan_Dto dto)
        {
            var data = await _merchant_IOC._merchant_EFCore.GetAll(d => d.MId == dto.id).SingleOrDefaultAsync();
            data.MIsBan = dto.isBan;
            _merchant_IOC._merchant_EFCore.Update(data);
            var result = await _merchant_IOC._merchant_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }


        /// <summary>
        /// 提交订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Merchant_CreateOrder(string mId, Add_Orders_Dto dto)
        {

            // 获取订单中的商品ID
            var gids = dto.orders!.Select(d => d.id).ToList();

            // 一次性查询所有商品信息并按供应商分组
            var goodsBySupplier = _goods_IOC._goods_EFCore
                .GetAll(d => gids.Contains(d.Gid))
                .ToList()
                .GroupBy(d => d.GSid)
                .ToList();


            // 所有商品类型字典数据
            var allType = _sys_IOC._sys_Dictionary_EFCore.GetAll().ToList();

            // 创建订单列表
            List<Order> orders = new List<Order>();

            // 为每个供应商创建一个订单
            goodsBySupplier.ForEach(d =>
            {

                var supplierGoods = d.ToList();
                // 生成该供应商订单的商品名称列表
                var goodsNames = string.Join(",", supplierGoods.Select(g => g.Gname));
                // 创建订单
                var order = new Order
                {
                    Oid = Config.GenerateOrderId(),
                    OacceptTime = null,
                    OcancelTime = null,
                    OcancelType = null,
                    OcompleteTime = null,
                    OcreateTime = DateTime.Now,
                    OisAccept = -1,
                    OisCancel = 0,
                    OisComplete = 0,
                    OisDirectly = 0,
                    OisReceive = 0,
                    OisSend = 0,
                    Omid = mId,
                    Osid = d.Key,
                    Omoney = dto.money,
                    OsendTime = null,
                    OreceiveTime = null,
                    Ototal = 0,
                    OgoodsNames = goodsNames,
                    OgoodsTypeCount = supplierGoods.Select(g => g.Gtype).Distinct().Count(),
                    OcurrMoney = dto.money,
                };
               
                orders.Add(order);
            });

            // 保存订单到数据库
            _merchant_IOC._orders_EFCore.AddRange(orders);
            _merchant_IOC._orders_EFCore.SaveChanges();

            // 创建订单详情列表
            List<OrderDetail> orderDetails = new List<OrderDetail>();

            // 为每个商品创建对应的订单详情
            foreach (var orderItem in dto.orders)
            {
                // 获取商品信息
                var goods = _goods_IOC._goods_EFCore.GetAll(e => e.Gid == orderItem.id).SingleOrDefault();

                // 查找该商品所属供应商的订单
                var order = orders.FirstOrDefault(o => o.Osid == goods.GSid);


                // 获取商品类型名称
                var typeName = allType
                    .Where(c => c.Did == goods.Gtype)
                    .Select(c => c.Dname)
                    .SingleOrDefault();
                var rawPrice = goods.GisPromote == 1
            ? orderItem.number * goods.GpromotePrice
            : orderItem.number * goods.Gprice;

                // 创建订单详情
                var detail = new OrderDetail
                {
                    OdId = Config.GenerateTId(),
                    OdCancelTime = null,
                    OdCompleteTime = null,
                    OdCreateTime = DateTime.Now,
                    OdCurrMoney = 0,
                    OdCurrNumber = 0,
                    OdGid = orderItem.id,
                    OdIsCancel = 0,
                    OdIsDirectly = 0,
                    OdIsComplete = 0,
                    OdIsPromote = goods.GisPromote,
                    OdIsReceive = 0,
                    OdIsSend = 0,
                    OdMid = mId,
                    OdMoney = Math.Round((double)rawPrice!, 2),
                    OdNumber = orderItem.number,
                    OdOid = order.Oid,
                    OdReceiveTime = null,
                    OdSendTime = null,
                    OdBirthday = goods.Gbirthday,
                    OdExpiryday = goods.Gexpiryday,
                    OdName = goods.Gname,
                    OdPhoto = goods.Gcover,
                    OdPrice = goods.Gprice,
                    OdPromotePrice = goods.GpromotePrice,
                    OdSpecs = goods.Gspecs,
                    OdSid = goods.GSid,
                    OdType = typeName
                };

                orderDetails.Add(detail);
            }

            // 保存订单详情到数据库
            _merchant_IOC._order_Details_EFCore.AddRange(orderDetails);
            _merchant_IOC._order_Details_EFCore.SaveChanges();

            //更新订单的total
            var allorder = _merchant_IOC._order_Details_EFCore.GetAll().ToList();
            orders.ForEach(d => {
                var orderDetail = allorder.FirstOrDefault(c => c.OdOid == d.Oid);
                if (orderDetail != null)
                {
                    // 如果每个订单可能有多个明细，应该用Count()
                    d.Ototal = allorder.Count(c => c.OdOid == d.Oid);
                    d.Omoney = allorder.Where(c => c.OdOid == d.Oid).Sum(c => c.OdMoney);
                    d.OcurrMoney = d.Omoney;
                }
                else
                {
                    // 处理找不到对应明细的情况
                    d.Ototal = 0;
                    d.Omoney = 0;
                    d.OcurrMoney = 0;
                }

            });

            _merchant_IOC._orders_EFCore.UpdateRange(orders);
            _merchant_IOC._orders_EFCore.SaveChanges();

            // 1. 更新商品库存和销量（复用查询结果）
            var orderGoods = _goods_IOC._goods_EFCore
                .GetAll(c => gids.Contains(c.Gid))
                .ToList();

            dto.orders.ForEach(d =>
            {
                var goods = orderGoods.FirstOrDefault(c => c.Gid == d.id);
                if (goods == null) return; // 跳过不存在的商品

                goods.Ginventory -= d.number;
                goods.Gsales += d.number;
                _goods_IOC._goods_EFCore.Update(goods); // 标记商品为待更新
            });

            //更新供应商的订单数量
            //查询商品对应的所有供应商id
            var sids = _goods_IOC._goods_EFCore
             .GetAll(d => gids.Contains(d.Gid))
             .Select(d => d.GSid)
             .ToList();

            var allSupplierOrders = _merchant_IOC._orders_EFCore.GetAll().ToList();

            //找到要修改的供应商
            var supplier = _supplier_IOC._supplier_EFCore.GetAll().ToList();
            supplier.ForEach(d =>
            {
                d.SorderCount = allSupplierOrders.Where(c => c.Osid == d.Sid).Count();//所有订单数
                d.ScancelOrderCount = allSupplierOrders.Where(c => c.Osid == d.Sid && c.OisCancel == 1 && c.OcancelType == 2).Count();//取消订单数
                d.ScompleteOrderCount = allSupplierOrders.Where(c => c.Osid == d.Sid && c.OisComplete == 1).Count();//订单完成数
                d.ScancelMoney = allSupplierOrders.Where(c => c.Osid == d.Sid && c.OisCancel == 1 && c.OcancelType == 2).Sum(c => c.Omoney);
                d.Smoney = allSupplierOrders.Where(c => c.Osid == d.Sid && c.OisComplete == 1).Sum(c => c.Omoney);
                d.ScurrMoney = allSupplierOrders.Where(c => c.Osid == d.Sid && c.OisComplete == 1).Sum(c => c.OcurrMoney);
            });
            _supplier_IOC._supplier_EFCore.UpdateRange(supplier);
            _supplier_IOC._supplier_EFCore.SaveChanges();

            //更新商户的订单数据
            //找到当前登录的商户
            var merchant = _merchant_IOC._merchant_EFCore.GetAll(d => d.MId == mId).Single();
            //找到当前商户的所有订单
            var allMerchantOrders = _merchant_IOC._orders_EFCore.GetAll(d => d.Omid == mId).ToList();

            merchant.MOrderCount = allMerchantOrders.Count();//订单数
            merchant.MCompleteOrderCount = allMerchantOrders.Where(d => d.OisComplete == 1).Count();//完成订单数
            merchant.MCancelOrderCount = allMerchantOrders.Where(d => d.OisCancel == 1 && d.OcancelType == 1).Count();//订单取消数
            merchant.MMoney = allMerchantOrders.Where(d => d.OisComplete == 1).Sum(d => d.Omoney);
            merchant.MCurrMoney = allMerchantOrders.Where(d => d.OisComplete == 1).Sum(d => d.OcurrMoney);//实际金额
            merchant.MCancelMoney = allMerchantOrders.Where(d => d.OisCancel == 1 && d.OcancelType == 1).Sum(d => d.Omoney);//取消金额

            _merchant_IOC._merchant_EFCore.Update(merchant);
            _merchant_IOC._merchant_EFCore.SaveChanges();



            // 2. 处理购物车
            var key = _configuration["Redis:Keys:Get_Car_Data"];
            var car = _redisListService.Get(key + mId);



            //清除redis
            var count = dto.orders.Count();

            var data = new List<CarDetails_Dto>();
            car.ForEach(d =>
            {
                data.Add(JsonConvert.DeserializeObject<CarDetails_Dto>(d));
            });


            for (int i = 0; i < count; i++)
            {

                string valueToRemove = dto.orders[i].id;//要移除的商品
                var removedata = data.Where(d => d.id == valueToRemove).SingleOrDefault();

                _redisListService.RemoveItemFromList(key + mId, JsonConvert.SerializeObject(removedata));
            }

            /*
                        // 获取购物车详情
                        var cardetails = _merchant_IOC._carDetails_EFCore
                            .GetAll(d => d.CdCId == car.CId)
                            .ToList();

                        // 筛选已下单的商品详情并标记为待删除
                        var cargoods = cardetails.Where(d => gids.Contains(d.CdGId)).ToList();
                        _merchant_IOC._carDetails_EFCore.DeleteRange(cargoods);

                        // 计算剩余商品总数并更新购物车
                        var remainingTotal = cardetails.Except(cargoods).Sum(d => d.CdNumber) ?? 0;
                        car.CTotal = remainingTotal;
                        _merchant_IOC._car_EFCore.Update(car); // 标记购物车为待更新

                        // 若购物车为空，标记为待删除
                        if (remainingTotal == 0)
                        {
                            _merchant_IOC._car_EFCore.Delete(car);
                        }*/

            var result = await _goods_IOC._goods_EFCore.SaveChangesAsync();
            return Get_Result(result);

        }

        /// <summary>
        /// 获取我的购物车
        /// </summary>
        /// <param name="mId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Merchant_GetMyCar(string mid)
        {
            var key = _configuration["Redis:Keys:Get_Car_Data"];
            var cars = _redisListService.Get(key + mid);

            var data = new List<CarDetails_Dto>();
            cars.ForEach(d =>
            {
                data.Add(JsonConvert.DeserializeObject<CarDetails_Dto>(d));
            });


            /*  //当前商户的购物车id
              var c_id = _merchant_IOC._car_EFCore.GetAll(d => d.CMId == mId).Select(d => d.CId).SingleOrDefault();
              //找到对应的购物车详情
              var data = await _merchant_IOC._carDetails_EFCore.GetAll(d => d.CdCId == c_id)
                  .Select(d => new CarDetails_Dto()
                  {
                      id = d.CdId,
                      gid = d.CdGId,
                      number = d.CdNumber,

                  }).ToListAsync();

              //所有商品
              var goods = _goods_IOC._goods_EFCore.GetAll().ToList();
              var supplier = _supplier_IOC._supplier_EFCore.GetAll().ToList();

              data.ForEach(d =>
              {
                  var g = goods.Where(c => c.Gid == d.gid).SingleOrDefault();
                  d.s_id = g.GSid;
                  var s = supplier.Where(c => c.Sid == d.s_id).SingleOrDefault();
                  d.specs = g.Gspecs;
                  d.price = g.GpromotePrice;
                  d.explain = g.Gexplain;
                  d.name = g.Gname;
                  d.photo = g.Gcover;
                  d.supplier = s.Sname;
                  d.isShelve = g.GisShelve;
                  d.inventory = g.Ginventory;
                  d.birthday = g.Gbirthday?.ToString("yyyy-MM-dd") ?? "";
                  d.expiryDate = g.Gbirthday?.AddDays(g.Gexpiryday ?? 0).ToString("yyyy-MM-dd") ?? "";
              });*/

            return Get_Result(0, "ok", data);

        }

        /// <summary>
        /// 更新购物车
        /// </summary>
        /// <param name="id"></param>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// 

        public async Task<Api_Result_Dto> Update_Cars(string? id, CarDetails_Dto[] dto)
        {
            var key = _configuration["Redis:Keys:Get_Car_Data"];

            var count = _redisListService.Count(key + id);

            for (int i = 0; i < count; i++)
            {
                _redisListService.RemoveStartFromList(key + id);
            }

            await Task.Delay(10);

            // 过滤掉数量为0的商品并序列化
            var data = dto
                .Where(item => item.carCount > 0) // 只保留数量大于0的商品
                .Select(item => JsonConvert.SerializeObject(item))
                .ToList();

            /*  var data = new List<string>();
              foreach (var d in dto)
              {
                  data.Add(JsonConvert.SerializeObject(d));
              }*/
            _redisListService.Add(key + id, data);//存进去
            return Get_Result(0, "ok");

        }

        /// <summary>
        /// 获取单个商品详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Merchant_GetSingleGoods(string? id)
        {
            var data = await _goods_IOC._goods_EFCore.GetAll(d => d.Gid == id)
                .Select(d => new GoodsDetails_Dto()
                {
                    id = d.Gid,
                    name = d.Gname,
                    explain = d.Gexplain,
                    sales = d.Gsales,
                    inventory = d.Ginventory,
                    price = d.Gprice,
                    photo = d.Gcover,
                    s_id = d.GSid,
                    specs = d.Gspecs,
                    carCount = 0,
                    birthday = d.Gbirthday.Value.ToString("yyyy-MM-dd"),
                    expiryday = d.Gexpiryday,
                    tId = d.Gtype
                }).SingleOrDefaultAsync();

            var promote = _promote_IOC._promote_EFCore.GetAll(d => d.Pgid == data.id);
            if (promote.Any())
            {
                data.promotePrice = _promote_IOC._promote_EFCore.
                  GetAll(false, o => o.PcreateTime, d => d.Pgid == data.id).
                  Select(d => d.PpromotePrice).First();

            }
            else {
                data.promotePrice = null;
            }

            var suppliers = _supplier_IOC._supplier_EFCore.GetAll(d => d.Sid==data.s_id);
            if (suppliers.Any())
            {
                data.supplierName = suppliers.Select(d => d.Sname).Single();
            }
            else
            {
                data.supplierName = null;
            }
           
            data.address = _supplier_IOC._supplier_EFCore.GetAll(d => d.Sid == data.s_id).Select(d => d.Saddress).SingleOrDefault();
            return Get_Result(0, "ok", data);
        }

        /// <summary>
        /// 从购物车移除商品
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Merchant_RemoveCar(Add_Car_Dto dto)
        {
            //获取当前商户的购物车id
            var c_id = _merchant_IOC._car_EFCore.GetAll(d => d.CMId == dto.mid).Select(d => d.CId).SingleOrDefault();

            var cardetails = _merchant_IOC._carDetails_EFCore.GetAll(d => d.CdCId == c_id).ToList();
            var goods = cardetails.Where(d => d.CdGId == dto.gid).SingleOrDefault();
            if (goods.CdNumber == 1)
            {
                _merchant_IOC._carDetails_EFCore.Delete(goods!);
            }
            else
            {
                goods.CdNumber = goods.CdNumber - 1;
                _merchant_IOC._carDetails_EFCore.Update(goods);
            }
            _merchant_IOC._carDetails_EFCore.SaveChanges();

            var changeCar = _merchant_IOC._car_EFCore.GetAll(d => d.CMId == dto.mid).SingleOrDefault();
            //获取当前购物车的所有数量
            changeCar.CTotal = _merchant_IOC._carDetails_EFCore.GetAll(d => d.CdCId == c_id).Select(d => d.CdNumber).Sum() ?? 0;
            _merchant_IOC._car_EFCore.Update(changeCar);
            _merchant_IOC._car_EFCore.SaveChanges();

            var data = _merchant_IOC._car_EFCore.GetAll(d => d.CMId == dto.mid && d.CTotal == 0).Any();
            if (data)
            {
                //有
                var del = _merchant_IOC._car_EFCore.GetAll(d => d.CMId == dto.mid).Single();
                _merchant_IOC._car_EFCore.Delete(del);

            }
            var result = await _merchant_IOC._car_EFCore.SaveChangesAsync();

            return Get_Result(result);
        }

        /// <summary>
        /// 商品搜索
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Merchant_SearchGoods(Fenye_Dto dto)
        {
            var supplier = _supplier_IOC._supplier_EFCore.GetAll().ToList();
            var data = await _goods_IOC._goods_EFCore
                .GetAll(out int total, dto.page, dto.limit, false, o => o.GcreateTime, d => d.Gname.Contains(dto.key))
                 .Select(d => new GoodsDetails_Dto
                 {
                     name = d.Gname,
                     id = d.Gid,
                     sales = d.Gsales,
                     specs = d.Gspecs,
                     explain = d.Gexplain,
                     inventory = d.Ginventory,
                     price = d.GisPromote==1?d.GpromotePrice:d.Gprice,
                     photo = d.Gcover,
                     s_id = d.GSid

                 }).ToListAsync();

            data.ForEach(d =>
            {
                d.supplierName = supplier.Where(c => c.Sid == d.s_id).Select(c => c.Sname).SingleOrDefault();

            });

            return Get_Result(0, "ok", new
            {
                data = data,
                total = total
            });
        }

        /// <summary>
        /// 获取商品的猜你喜欢
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Merchant_GetLikeGoods(string? gid, string? tid)
        {
            //找到当前类型的所有商品
            var data = await _goods_IOC._goods_EFCore.GetAll(d => d.Gtype == tid && d.Gid != gid)
                 .Select(d => new Goods_Dto
                 {
                     id = d.Gid,
                     specs = d.Gspecs,
                     name = d.Gname,
                     explain = d.Gexplain,
                     price = d.GisPromote == 1 ? d.GpromotePrice : d.Gprice,
                     photo = d.Gcover,
                     inventory = d.Ginventory,
                     sales = d.Gsales,
                     s_id = d.GSid,
                 }).ToListAsync();

            var supplier = _supplier_IOC._supplier_EFCore.GetAll().ToList();
            data.ForEach(d =>
            {

                d.supplierName = supplier.Where(e => e.Sid == d.s_id).Select(c => c.Sname).SingleOrDefault();
            });

            if (!data.Any()) {
                //如果没有显示所有商品
                data = await _goods_IOC._goods_EFCore.GetAll()
                  .Select(d => new Goods_Dto
                  {
                      id = d.Gid,
                      specs = d.Gspecs,
                      name = d.Gname,
                      explain = d.Gexplain,
                      price = d.GisPromote == 1 ? d.GpromotePrice : d.Gprice,
                      photo = d.Gcover,
                      inventory = d.Ginventory,
                      sales = d.Gsales,
                      s_id = d.GSid,
                  }).ToListAsync();

            
                data.ForEach(d =>
                {

                    d.supplierName = supplier.Where(e => e.Sid == d.s_id).Select(c => c.Sname).SingleOrDefault();
                });
            }

            return Get_Result(0, "ok", data);
        }

        /// <summary>
        /// 获取商户的订单
        /// </summary>
        /// <param name="fenye_Dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Merchant_Get_Orders(Fenye_Dto dto)
        {
            Expression<Func<Order, bool>> where = dto.type switch
            {
                1 => d => (d.Omid == dto.id && d.OisAccept == -1 && d.OisComplete == 0 && d.OisCancel == 0),//未接单
                2 => d => (d.Omid == dto.id && d.OisAccept == 1 && d.OisCancel == 0 && d.OisComplete==0),//进行中
                3 => d => (d.Omid == dto.id && d.OisComplete == 1 && d.OisReceive == 1 && d.OisSend == 1),//已完成
                4 => d => (d.Omid == dto.id && d.OisCancel == 1 && d.OcancelType == 1),//已取消 1代表商户取消
            };


            var data = await _merchant_IOC._orders_EFCore
                .GetAll(out int total, dto.page, dto.limit, false, o => o.OcreateTime, where)
                .Select(d => new MerchantOrders_Dto()
                {
                    id = d.Oid,
                    isAccept = d.OisAccept,
                    isCancel = d.OisCancel,
                    isComplete = d.OisComplete,
                    isReceive = d.OisReceive,
                    isSend = d.OisSend,
                    money = d.Omoney,
                    sid = d.Osid,
                    cancelTime = d.OcancelTime.Value.ToString("yyyy-MM-dd HH:mm:ss"), //取消订单时间
                    completeTime = d.OcompleteTime.Value.ToString("yyyy-MM-dd HH:mm:ss"), //完成时间
                    sendTime = d.OsendTime.Value.ToString("yyyy-MM-dd HH:mm:ss"), //发货时间
                    time = d.OcreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss"), //创建时间/下单时间
                    receiveTime = d.OreceiveTime.Value.ToString("yyyy-MM-dd HH:mm:ss") //收货时间
                }).ToListAsync();

            //获取所有供应商
            var supplier = _supplier_IOC._supplier_EFCore.GetAll().ToList();
            //获取所有商品详情
            var details = _merchant_IOC._order_Details_EFCore.GetAll()
                .Select(e => new Merchant_OrderDetails_Dto()
                {
                    id = e.OdId,
                    oid = e.OdOid,
                    gid = e.OdGid,
                    number = e.OdNumber,
                    name = e.OdName,
                    isCancel = e.OdIsCancel,
                    isComplete = e.OdIsComplete,
                    isDirectly = e.OdIsDirectly,
                    isPromote = e.OdIsPromote,
                    isReceive = e.OdIsReceive,
                    isSend = e.OdIsSend,
                    photo = e.OdPhoto,
                    price = e.OdIsPromote == 1 ? e.OdPromotePrice : e.OdPrice,
                    specs = e.OdSpecs,
                    d_brithday = e.OdBirthday,
                    d_cancelTime = e.OdCancelTime,
                    d_sendTime = e.OdSendTime,
                    d_expiryDate = e.OdExpiryday


                }).ToList();
            details.ForEach(e =>
            {
                e.brithday = e.d_brithday?.ToString("yyyy-MM-dd");
                e.expiryDate = e.d_brithday?.AddDays(e.d_expiryDate ?? 0).ToString("yyyy-MM-dd");
                e.cancelTime = e.d_cancelTime?.ToString("yyyy-MM-dd HH:mm:ss");
                e.sendTime = e.d_sendTime?.ToString("yyyy-MM-dd HH:mm:ss");
            });

            data.ForEach(d =>
            {
                d.supplier = supplier.Where(c => c.Sid == d.sid).Select(c => c.Sname).SingleOrDefault();
                d.goods = details.Where(c => c.oid == d.id).ToList();
            });

            return Get_Result(0, "ok", new
            {
                total = total,
                data = data
            });
        }

        /// <summary>
        /// 商户取消订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Merchant_CancelOrder(IsBan_Dto dto)
        {
            var data = await _merchant_IOC._orders_EFCore.GetAll(d => d.Oid == dto.id).SingleOrDefaultAsync();
            data!.OisCancel = dto.isCancel;
            data!.OcancelTime = DateTime.Now;
            data!.OcancelType = 1;//商户取消
            _merchant_IOC._orders_EFCore.Update(data);
            _merchant_IOC._orders_EFCore.SaveChanges();


            //修改商户的取消订单
            var merchant = await _merchant_IOC._merchant_EFCore.GetAll(d => d.MId == dto.mid).SingleOrDefaultAsync();
            merchant!.MCancelOrderCount += 1;
            _merchant_IOC._merchant_EFCore.Update(merchant);

            var result = await _merchant_IOC._merchant_EFCore.SaveChangesAsync();

            return Get_Result(result);
        }

        /// <summary>
        /// 商户-获取订单统计数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Merchant_GetMeStatistics(string? id)
        {
            //获取当前商户的所有订单信息
            var order = await _merchant_IOC._orders_EFCore.GetAll(d => d.Omid == id).ToListAsync();
            Merchant_Statistics_Dto data = new Merchant_Statistics_Dto()
            {
                allOrderCount=order.Count(),
                completeOrderCount = order.Where(d => d.OisComplete == 1).Count(),
                cancelOrderCount = order.Where(d => d.OisCancel == 1).Count(),//商户取消订单
                noSendOrderCount = order.Where(d => d.OisSend == 0 && d.OisCancel == 0 && d.OisAccept!=0).Count(),
                sendOrderCount = order.Where(d => d.OisSend == 1 && d.OisCancel == 0 && d.OisComplete==0).Count(),
                money = Math.Round(order.Where(d => d.OisComplete == 1).Sum(d => d.Omoney) ?? 0, 2)
        };

            return Get_Result(0, "ok", data);

        }

        /// <summary>
        /// 获取单个商户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Single_Merchant(string? id)
        {
            var data = await _merchant_IOC._merchant_EFCore
                .GetAll(d => d.MId == id)
                .Select(d => new Merchant_Single_Dto()
                {
                    mid = d.MId,
                    name = d.MName,
                    account = d.MAccount,
                    isActive = d.MIsActive,
                    cancelMoney = d.MCancelMoney,
                    cancelOrderCount = d.MCancelOrderCount,
                    completeOrderCount = d.MCompleteOrderCount,
                    contact = d.MContacts,
                    orderCount = d.MOrderCount,
                    isBan = d.MIsBan,
                    money = d.MMoney,
                    currmoney=d.MCurrMoney,
                    time = d.MCreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss")
                }).SingleOrDefaultAsync();

            //获取所有订单
            var orders = _merchant_IOC._orders_EFCore.GetAll().ToList();

            data.buyGoodsCount = orders.Where(c => c.Omid == data.mid).Sum(d => d.Ototal);
            data.receiveOrderCount = orders.Where(c => c.Omid == data.mid && c.OisReceive == 1).Count();
            data.sendOrderCount = orders.Where(c => c.Omid == data.mid && c.OisSend == 1).Count();

            return Get_Result(0, "ok", data);


        }

        /// <summary>
        /// 获取商户的订单列表
        /// </summary>
        /// <param name="fenye_Dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Merchant_Order(Fenye_Dto dto)
        {
            var data =await _merchant_IOC._orders_EFCore
                 .GetAll(out int total, dto.page, dto.limit, false, o => o.OcreateTime, d => d.Omid == dto.id)
                 .Select(d => new MerchantOrders_Dto(){ 
                 id=d.Oid,
                 isAccept=d.OisAccept,
                 goodsName=d.OgoodsNames,
                 number=d.Ototal,
                 money=d.Omoney,
                 time=d.OcreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                 sid=d.Osid,
                 mid=d.Omid
                      
                 }).ToListAsync();
            var supplier = _supplier_IOC._supplier_EFCore.GetAll().ToList();
            var merchant = _merchant_IOC._merchant_EFCore.GetAll().ToList();
            data.ForEach(d => {
                d.supplier = supplier.Where(c => c.Sid == d.sid).Select(c => c.Sname).SingleOrDefault();
                d.merchant = merchant.Where(c => c.MId == d.mid).Select(c => c.MName).SingleOrDefault();

            });

            return Get_Result(0, "ok", new { 
            data=data,
            total=total
            });
        }

        /// <summary>
        /// 获取单个订单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Merchant_GetSingleOrder(string? id)
        {
            var data =await _merchant_IOC._orders_EFCore.GetAll(d => d.Oid == id)
                .Select(d => new MerchantOrders_Dto(){ 
                id=d.Oid,
                sid=d.Osid,
                
                time=d.OcreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss")
                }).SingleOrDefaultAsync();

            var goods = _merchant_IOC._order_Details_EFCore.GetAll()
                .Select(d => new Merchant_OrderDetails_Dto(){ 
                id=d.OdId,
                oid=d.OdOid,
                gid=d.OdGid,
                price=d.OdIsPromote==1?d.OdPromotePrice:d.OdPrice,
                number=d.OdNumber,
                name=d.OdName,
                photo=d.OdPhoto,
                specs=d.OdSpecs,
                
                }).ToList();

            var supplier = _supplier_IOC._supplier_EFCore.GetAll().ToList();

            data.goods = goods.Where(d => d.oid == data.id).ToList();
            data.supplier = supplier.Where(d => d.Sid == data.sid).Select(d=>d.Sname).SingleOrDefault();

            return Get_Result(0, "ok", data);

        
        }

        /// <summary>
        /// 商户-收货
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Merchant_ReceiveGoods(string? id)
        {
            var order =await _merchant_IOC._orders_EFCore.GetAll(d => d.Oid == id).SingleOrDefaultAsync();
            order.OisComplete = 1;
            order.OcompleteTime = DateTime.Now;
            order.OisReceive = 1;
            order.OreceiveTime = DateTime.Now;
            _merchant_IOC._orders_EFCore.Update(order);

            var orderdetails =await _merchant_IOC._order_Details_EFCore.GetAll(d => d.OdOid == id).ToListAsync();
            orderdetails.ForEach(d => {
                d.OdIsComplete = 1;
                d.OdIsReceive = 1;
                d.OdCompleteTime = DateTime.Now;
                d.OdReceiveTime = DateTime.Now;
            });
          
            _merchant_IOC._order_Details_EFCore.UpdateRange(orderdetails);
            _merchant_IOC._orders_EFCore.Transactions(_merchant_IOC._order_Details_EFCore);
            //修改商户中的成交额和已完成数量
            //获取所有商户
            var merchant = _merchant_IOC._merchant_EFCore.GetAll().ToList();
            //获取所有已收货订单
            var allOrder = _merchant_IOC._orders_EFCore.GetAll(d => d.OisReceive == 1).ToList();
            merchant.ForEach(d => {
                d.MCompleteOrderCount = allOrder.Where(c => c.Omid == d.MId).Count();
                d.MCurrMoney = allOrder.Where(c => c.Omid == d.MId).Sum(c => c.Omoney);
            });
            _merchant_IOC._merchant_EFCore.UpdateRange(merchant);

            //修改供应商的成交额和已完成数量
            //获取所有供应商
            var supplier = _supplier_IOC._supplier_EFCore.GetAll().ToList();
            supplier.ForEach(d => {
                d.ScompleteOrderCount = allOrder.Where(c => c.Osid == d.Sid).Count();
                d.ScurrMoney = allOrder.Where(c => c.Osid == d.Sid).Sum(c => c.Omoney);
            });
            _supplier_IOC._supplier_EFCore.UpdateRange(supplier);

            var result = _merchant_IOC._merchant_EFCore.Transactions(_supplier_IOC._supplier_EFCore);
            return Get_Result(result?0:-1);
        }

        /// <summary>
        /// 商户-获取我的订单详情
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Merchant_GetAllOrder(Fenye_Dto dto)
        {
            Expression<Func<Order, bool>> where = dto.type switch
            {
                1 => d => (d.Omid == dto.id),//全部
                2 => d => (d.Omid == dto.id && d.OisComplete == 1 && d.OisReceive == 1 && d.OisSend == 1),//已完成
                3 => d => (d.Omid == dto.id && d.OisAccept == 1 && d.OisSend==1 && d.OisComplete==0),//已发货
                4 => d => (d.Omid == dto.id && d.OisAccept == 1 && d.OisSend == 0),//未发货
                5 => d => (d.Omid == dto.id && d.OisCancel == 1),//已取消
            };


            var data = await _merchant_IOC._orders_EFCore
                .GetAll(out int total, dto.page, dto.limit, false, o => o.OcreateTime, where)
                .Select(d => new MerchantOrders_Dto()
                {
                    id = d.Oid,
                    isAccept = d.OisAccept,
                    isCancel = d.OisCancel,
                    isComplete = d.OisComplete,
                    isReceive = d.OisReceive,
                    isSend = d.OisSend,
                    money = d.Omoney,
                    sid = d.Osid,
                    cancelTime = d.OcancelTime.Value.ToString("yyyy-MM-dd HH:mm:ss"), //取消订单时间
                    completeTime = d.OcompleteTime.Value.ToString("yyyy-MM-dd HH:mm:ss"), //完成时间
                    sendTime = d.OsendTime.Value.ToString("yyyy-MM-dd HH:mm:ss"), //发货时间
                    time = d.OcreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss"), //创建时间/下单时间
                    receiveTime = d.OreceiveTime.Value.ToString("yyyy-MM-dd HH:mm:ss") //收货时间
                }).ToListAsync();

            //获取所有供应商
            var supplier = _supplier_IOC._supplier_EFCore.GetAll().ToList();
            //获取所有商品详情
            var details = _merchant_IOC._order_Details_EFCore.GetAll()
                .Select(e => new Merchant_OrderDetails_Dto()
                {
                    id = e.OdId,
                    oid = e.OdOid,
                    gid = e.OdGid,
                    number = e.OdNumber,
                    name = e.OdName,
                    isCancel = e.OdIsCancel,
                    isComplete = e.OdIsComplete,
                    isDirectly = e.OdIsDirectly,
                    isPromote = e.OdIsPromote,
                    isReceive = e.OdIsReceive,
                    isSend = e.OdIsSend,
                    photo = e.OdPhoto,
                    price = e.OdIsPromote == 1 ? e.OdPromotePrice : e.OdPrice,
                    specs = e.OdSpecs,
                    d_brithday = e.OdBirthday,
                    d_cancelTime = e.OdCancelTime,
                    d_sendTime = e.OdSendTime,
                    d_expiryDate = e.OdExpiryday


                }).ToList();
            details.ForEach(e =>
            {
                e.brithday = e.d_brithday?.ToString("yyyy-MM-dd");
                e.expiryDate = e.d_brithday?.AddDays(e.d_expiryDate ?? 0).ToString("yyyy-MM-dd");
                e.cancelTime = e.d_cancelTime?.ToString("yyyy-MM-dd HH:mm:ss");
                e.sendTime = e.d_sendTime?.ToString("yyyy-MM-dd HH:mm:ss");
            });

            data.ForEach(d =>
            {
                d.supplier = supplier.Where(c => c.Sid == d.sid).Select(c => c.Sname).SingleOrDefault();
                d.goods = details.Where(c => c.oid == d.id).ToList();
            });

            return Get_Result(0, "ok", new
            {
                total = total,
                data = data
            });
        }

        /// <summary>
        /// 商户-获取热门商品
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Merchant_GetHotGoods()
        {
            var data = await _goods_IOC._goods_EFCore.GetAll(d => d.GisPromote == 0 && d.GisShelve==1)
                .Select(d => new Merchant_HotGoods_Dto()
                {
                    id = d.Gid,
                    carCount = 0,
                    explain = d.Gexplain,
                    inventory = d.Ginventory,
                    name = d.Gname,
                    photo = d.Gcover,
                    price = d.Gprice,
                    sales = d.Gsales,
                    specs = d.Gspecs,
                    s_id = d.GSid
                }).ToListAsync();
            var supplier = _supplier_IOC._supplier_EFCore.GetAll().ToList();
            data.ForEach(d => {
                d.supplier = supplier.Where(c => c.Sid == d.s_id).Select(c => c.Sname).SingleOrDefault();
            });

            return Get_Result(0, "ok", data);
        }

        /// <summary>
        /// 获取热卖榜单商品
        /// </summary>
        /// <param name="fenye_Dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Merchant_GetHotBuyGoods(Fenye_Dto dto)
        {
            var data = await _goods_IOC._goods_EFCore.GetAll(
                out int total,dto.page,dto.limit,false,o=>o.Gsales,d=>d.GisShelve==1)
              .Select(d => new Merchant_HotGoods_Dto()
              {
                  id = d.Gid,
                  carCount = 0,
                  explain = d.Gexplain,
                  inventory = d.Ginventory,
                  name = d.Gname,
                  photo = d.Gcover,
                  price = d.GisPromote==1?d.GpromotePrice:d.Gprice,
                  sales = d.Gsales,
                  specs = d.Gspecs,
                  s_id = d.GSid
              }).ToListAsync();
            var supplier = _supplier_IOC._supplier_EFCore.GetAll().ToList();
            data.ForEach(d => {
                d.supplier = supplier.Where(c => c.Sid == d.s_id).Select(c => c.Sname).SingleOrDefault();
            });

            return Get_Result(0, "ok", data);
        }

        /// <summary>
        /// 获取未发货的订单
        /// </summary>
        /// <param name="fenye_Dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Merchant_Me_GetNoSendOrder(Fenye_Dto dto)
        {
            var data = await _merchant_IOC._orders_EFCore
               .GetAll(out int total, dto.page, dto.limit, false, o => o.OcreateTime,
               d=>d.OisSend==0 && d.OisCancel==0 && d.Omid==dto.id && d.OisAccept!=0)
               .Select(d => new MerchantOrders_Dto()
               {
                   id = d.Oid,
                   isAccept = d.OisAccept,
                   isCancel = d.OisCancel,
                   isComplete = d.OisComplete,
                   isReceive = d.OisReceive,
                   isSend = d.OisSend,
                   money = d.Omoney,
                   sid = d.Osid,
                   cancelTime = d.OcancelTime.Value.ToString("yyyy-MM-dd HH:mm:ss"), //取消订单时间
                   completeTime = d.OcompleteTime.Value.ToString("yyyy-MM-dd HH:mm:ss"), //完成时间
                   sendTime = d.OsendTime.Value.ToString("yyyy-MM-dd HH:mm:ss"), //发货时间
                   time = d.OcreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss"), //创建时间/下单时间
                   receiveTime = d.OreceiveTime.Value.ToString("yyyy-MM-dd HH:mm:ss") //收货时间
               }).ToListAsync();

            //获取所有供应商
            var supplier = _supplier_IOC._supplier_EFCore.GetAll().ToList();
            //获取所有商品详情
            var details = _merchant_IOC._order_Details_EFCore.GetAll()
                .Select(e => new Merchant_OrderDetails_Dto()
                {
                    id = e.OdId,
                    oid = e.OdOid,
                    gid = e.OdGid,
                    number = e.OdNumber,
                    name = e.OdName,
                    isCancel = e.OdIsCancel,
                    isComplete = e.OdIsComplete,
                    isDirectly = e.OdIsDirectly,
                    isPromote = e.OdIsPromote,
                    isReceive = e.OdIsReceive,
                    isSend = e.OdIsSend,
                    photo = e.OdPhoto,
                    price = e.OdIsPromote == 1 ? e.OdPromotePrice : e.OdPrice,
                    specs = e.OdSpecs,
                    d_brithday = e.OdBirthday,
                    d_cancelTime = e.OdCancelTime,
                    d_sendTime = e.OdSendTime,
                    d_expiryDate = e.OdExpiryday


                }).ToList();
            details.ForEach(e =>
            {
                e.brithday = e.d_brithday?.ToString("yyyy-MM-dd");
                e.expiryDate = e.d_brithday?.AddDays(e.d_expiryDate ?? 0).ToString("yyyy-MM-dd");
                e.cancelTime = e.d_cancelTime?.ToString("yyyy-MM-dd HH:mm:ss");
                e.sendTime = e.d_sendTime?.ToString("yyyy-MM-dd HH:mm:ss");
            });

            data.ForEach(d =>
            {
                d.supplier = supplier.Where(c => c.Sid == d.sid).Select(c => c.Sname).SingleOrDefault();
                d.goods = details.Where(c => c.oid == d.id).ToList();
            });

            return Get_Result(0, "ok", new
            {
                total = total,
                data = data
            });
        }

        /// <summary>
        /// 获取已取消的订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Api_Result_Dto> Merchant_Me_GetCancelOrder(Fenye_Dto dto)
        {
            var data = await _merchant_IOC._orders_EFCore
               .GetAll(out int total, dto.page, dto.limit, false, o => o.OcreateTime,
               d => d.OisCancel ==1 && d.Omid==dto.id)
               .Select(d => new MerchantOrders_Dto()
               {
                   id = d.Oid,
                   isAccept = d.OisAccept,
                   isCancel = d.OisCancel,
                   isComplete = d.OisComplete,
                   isReceive = d.OisReceive,
                   isSend = d.OisSend,
                   money = d.Omoney,
                   sid = d.Osid,
                   cancelTime = d.OcancelTime.Value.ToString("yyyy-MM-dd HH:mm:ss"), //取消订单时间
                   completeTime = d.OcompleteTime.Value.ToString("yyyy-MM-dd HH:mm:ss"), //完成时间
                   sendTime = d.OsendTime.Value.ToString("yyyy-MM-dd HH:mm:ss"), //发货时间
                   time = d.OcreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss"), //创建时间/下单时间
                   receiveTime = d.OreceiveTime.Value.ToString("yyyy-MM-dd HH:mm:ss") //收货时间
               }).ToListAsync();

            //获取所有供应商
            var supplier = _supplier_IOC._supplier_EFCore.GetAll().ToList();
            //获取所有商品详情
            var details = _merchant_IOC._order_Details_EFCore.GetAll()
                .Select(e => new Merchant_OrderDetails_Dto()
                {
                    id = e.OdId,
                    oid = e.OdOid,
                    gid = e.OdGid,
                    number = e.OdNumber,
                    name = e.OdName,
                    isCancel = e.OdIsCancel,
                    isComplete = e.OdIsComplete,
                    isDirectly = e.OdIsDirectly,
                    isPromote = e.OdIsPromote,
                    isReceive = e.OdIsReceive,
                    isSend = e.OdIsSend,
                    photo = e.OdPhoto,
                    price = e.OdIsPromote == 1 ? e.OdPromotePrice : e.OdPrice,
                    specs = e.OdSpecs,
                    d_brithday = e.OdBirthday,
                    d_cancelTime = e.OdCancelTime,
                    d_sendTime = e.OdSendTime,
                    d_expiryDate = e.OdExpiryday


                }).ToList();
            details.ForEach(e =>
            {
                e.brithday = e.d_brithday?.ToString("yyyy-MM-dd");
                e.expiryDate = e.d_brithday?.AddDays(e.d_expiryDate ?? 0).ToString("yyyy-MM-dd");
                e.cancelTime = e.d_cancelTime?.ToString("yyyy-MM-dd HH:mm:ss");
                e.sendTime = e.d_sendTime?.ToString("yyyy-MM-dd HH:mm:ss");
            });

            data.ForEach(d =>
            {
                d.supplier = supplier.Where(c => c.Sid == d.sid).Select(c => c.Sname).SingleOrDefault();
                d.goods = details.Where(c => c.oid == d.id).ToList();
            });

            return Get_Result(0, "ok", new
            {
                total = total,
                data = data
            });
        }
    }
}
